package org.dwell.vertx3.demos.jdbc;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.jdbc.spi.impl.HikariCPDataSourceProvider;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by JianGuo on 2016/1/21.
 */
public class JdbcVerticle extends AbstractVerticle {

    private Vertx vertx;
    private JDBCClient jdbcClient;

    @Override
    public void init(Vertx vertx, Context context)  {
        this.vertx = vertx;

        HikariCPDataSourceProvider provider = new HikariCPDataSourceProvider();

        JsonObject configuration = new JsonObject();
        configuration.put("foo", "bar");
        configuration.put("jdbcUrl", "jdbc:mysql://127.0.0.1:3306/web_easyui");
        configuration.put("driver_class", "com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
        configuration.put("username", "root");
        configuration.put("password", "");
        configuration.put("max_pool_size", 100);
        configuration.put("maxLifetime", 200L);

        try {
            DataSource dataSource = provider.getDataSource(configuration);
            String resource = "vertx3/demos/mapper-config.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder().build();
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(reader);
            Environment.Builder builder = new Environment.Builder("development");
            builder.dataSource(dataSource);
            Environment env = builder.build();
            sqlSessionFactory.getConfiguration().setEnvironment(env);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void start() throws Exception {

    }

    @Override
    public void stop() throws Exception {
        this.vertx.close();
    }

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(new JdbcVerticle());
    }
}
